'use strict';
// Copyright 2014 Blueant Inc. All Rights Reserved.

/**
 * @fileoverview 装备
 * @author sundbcn@gmail.com (sun debing)
 */

var equipConf = require('../config/equipConf');
var dataApi = require('../libs/dataApi');
var _ = require('lodash');
var randomUtil = require('../util/randomUtil');

exports.generateAdditiveAttr = function (equip_type, attr_type) {
    return _generateAdditiveAttr(equip_type, attr_type);
};

/**
 * 随机生成装备
 * @param  {[type]} equip_type [description]
 * @return {[type]}            [description]
 */
exports.generateEquip = function (equip_type) {
    var equipment_conf = equipConf.getEquipTypeConf(equip_type);
    if (!equipment_conf) {
        console.error('equip type can not found:' + equip_type);
        return null;
    }

    var hole_num = _.random(
        equipment_conf.min_hole_num,
        equipment_conf.max_hole_num
    );

    // 随机出附加的属性
    var additive_attr_list = [];
    var attr_type_list = [];
    var equipment_attr_conf = dataApi.equipment_attr.findById(equipment_conf.attr_id);

    _.each(equipment_attr_conf, function (equipment_attr_item) {
        attr_type_list.push(equipment_attr_item.attr_type);
    });

    _.each(attr_type_list, function (attr_type) {
        if (!dataApi.additive_attribute.findById(attr_type)) {
            return;
        }
        var attr = _generateAdditiveAttr(equip_type, attr_type);
        if (attr) {
            additive_attr_list.push(attr);
        }
    });

    return {
        equip_type: equip_type,
        hole_num: hole_num,
        additive_attr_list: additive_attr_list
    };
};

/**
 * 生成装备的随机属性
 * @param  {[type]} equip_type           [description]
 * @param  {[type]} filter_property_list [description]
 * @param  {[type]} gen_num              [description]
 * @return {[type]}                      [description]
 */
var _generateAdditiveAttr = function (equip_type, attr_type) {
    var equipment_conf = equipConf.getEquipTypeConf(equip_type);
    if (!equipment_conf) {
        console.error('equip type can not found:' + equip_type);
        return null;
    }

    var attr_list = [];
    dataApi.additive_attribute.each(function (value, key) {
        if (value.property != attr_type) {
            return;
        }
        var quality_list = value.quality.split(',');
        if (_.indexOf(quality_list, String(equipment_conf.quality)) !== -1) {
            attr_list.push(value);
        }
    });

    var attr = randomUtil.sample(attr_list);
    if (!!attr) {
        return attr.id;
    }
    return null;
};
